<script setup>
import { User, Lock, Filter } from "@element-plus/icons-vue";
import { ref, watch } from "vue";
import { getCode, postLogin } from "@/api/login";
import { postUserRegister } from "@/api/register";
import { useUserStore } from "@/stores";
import router from "@/router";

const isRegister = ref(false);
const form = ref(null);
// 验证码链接
const code = ref("");

const userStore = useUserStore();

// 注册
// 获取表单数据
const ruleForm = ref({
  username: "",
  password: "",
  repassword: "",
  captchaKey: "",
  captchaCode: "",
});

// 登录请求参数
const loginInfo = ref({
  username: "",
  password: "",
  captchaKey: "",
  captchaCode: "",
});

// 配置表单验证规则
const rules = {
  username: [
    { required: true, message: "请输入用户名", trigger: "blur" },
    { min: 5, max: 10, message: "用户名必须是5-10位的字符", trigger: "blur" },
  ],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    {
      pattern: /^\S{6,15}$/,
      message: "密码必须是6-15位的非空字符",
      trigger: "blur",
    },
  ],
  captchaCode: [
    { required: true, message: "请输入验证码", trigger: "blur" },
    { min: 5, max: 5, message: "验证码必须是5位字符", trigger: "blur" },
  ],
  repassword: [
    { required: true, message: "请再次输入密码", trigger: "blur" },
    {
      pattern: /^\S{6,15}$/,
      message: "密码必须是6-15位的非空字符",
      trigger: "blur",
    },
    // 自定义校验
    {
      validator: (rule, value, callback) => {
        if (value !== ruleForm.value.password) {
          callback(new Error("两次密码不一样！"));
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
  ],
};

// 获取验证码
const getCaptcha = async () => {
  const res = await getCode();
  ruleForm.value.captchaKey = res.data.data.key;
  loginInfo.value.captchaKey = res.data.data.key;
  code.value = res.data.data.image;
  // console.log(res);
};
getCaptcha();
// 60s 更换一个验证码
setInterval(() => {
  getCaptcha();
}, 60000);

// 点击注册按钮 就行预校验
const register = async () => {
  await form.value.validate();
  console.log(ruleForm.value);

  // // 发送请求
  const res = await postUserRegister({
    username: ruleForm.value.username,
    password: ruleForm.value.password,
    captchaKey: ruleForm.value.captchaKey,
    captchaCode: ruleForm.value.captchaCode,
  });

  // 提示注册成功
  ElMessage({
    message: "注册成功",
    type: "success",
  });
  //跳转到登录
  isRegister.value = false;
};

// 登录
// 点击登录按钮 就行预校验
const login = async () => {
  await form.value.validate();
  //  console.log(loginInfo.value);

  // 发送请求
  const res = await postLogin(loginInfo.value);
  // console.log(res);

  // 提示登录成功
  ElMessage({
    message: "登录成功",
    type: "success",
  });
  // 保存token 到仓库
  userStore.setToken(res.data.data);

  // 保存用户信息 到仓库
  await userStore.setUserInfo();

  const roleType = userStore.userInfo.roleType;

  if (roleType === 3) {
    // 跳转到管理员页面
    router.push("/admin");
  } else {
    // 跳转到用户页面
    console.log("跳转到用户页面");

    router.push("/home");
  }
};

// 表单切换时清空表单数据
watch(isRegister, () => {
  // 重新获取验证码
  getCaptcha();
  form.value.resetFields();
});
</script>

<template>
  <!-- el-row 一行分为24分 -->
  <!-- offset 左侧空隙份数 -->
  <el-row class="login-page">
    <el-col :span="12" class="bg"></el-col>
    <el-col :span="6" :offset="3" class="form">
      <!-- 注册 -->
      <el-form
        ref="form"
        size="large"
        autocomplete="off"
        v-if="isRegister"
        :model="ruleForm"
        :rules="rules"
      >
        <el-form-item>
          <h1>注册</h1>
        </el-form-item>
        <el-form-item prop="username">
          <el-input
            :prefix-icon="User"
            placeholder="请输入用户名"
            v-model="ruleForm.username"
          ></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            v-model="ruleForm.password"
            :prefix-icon="Lock"
            type="password"
            placeholder="请输入密码"
          ></el-input>
        </el-form-item>
        <el-form-item prop="repassword">
          <el-input
            v-model="ruleForm.repassword"
            :prefix-icon="Lock"
            type="password"
            placeholder="请输入再次密码"
          ></el-input>
        </el-form-item>
        <el-form-item prop="captchaCode">
          <el-row :gutter="20">
            <el-col :span="16">
              <el-input
                name="captchaCode"
                :prefix-icon="Filter"
                placeholder="请输入验证码"
                v-model="ruleForm.captchaCode"
              ></el-input>
            </el-col>
            <el-col :span="8">
              <el-image
                :src="code"
                style="width: 100px; height: 40px; cursor: pointer"
                @click="getCaptcha"
              />
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item>
          <el-button
            class="button"
            type="primary"
            auto-insert-space
            @click="register"
          >
            注册
          </el-button>
        </el-form-item>
        <el-form-item class="flex">
          <el-link type="info" underline="never" @click="isRegister = false">
            ← 返回
          </el-link>
        </el-form-item>
      </el-form>

      <!-- 登录 -->
      <el-form
        ref="form"
        size="large"
        autocomplete="off"
        :model="loginInfo"
        :rules="rules"
        v-else
      >
        <el-form-item>
          <h1>登录</h1>
        </el-form-item>
        <el-form-item prop="username">
          <el-input
            :prefix-icon="User"
            placeholder="请输入用户名"
            v-model="loginInfo.username"
          ></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            name="password"
            :prefix-icon="Lock"
            type="password"
            placeholder="请输入密码"
            v-model="loginInfo.password"
          ></el-input>
        </el-form-item>
        <el-form-item prop="captchaCode">
          <el-row :gutter="20">
            <el-col :span="16">
              <el-input
                name="captchaCode"
                :prefix-icon="Filter"
                placeholder="请输入验证码"
                v-model="loginInfo.captchaCode"
              ></el-input>
            </el-col>
            <el-col :span="8">
              <el-image
                :src="code"
                style="width: 100px; height: 40px; cursor: pointer"
                @click="getCaptcha"
              />
            </el-col>
          </el-row>
        </el-form-item>

        <el-form-item class="flex">
          <div class="flex">
            <el-checkbox>记住我</el-checkbox>
            <el-link type="primary" underline="never">忘记密码？</el-link>
          </div>
        </el-form-item>
        <el-form-item>
          <el-button
            class="button"
            type="primary"
            auto-insert-space
            @click="login"
            >登录</el-button
          >
        </el-form-item>
        <el-form-item class="flex">
          <el-link type="info" underline="never" @click="isRegister = true">
            注册 →
          </el-link>
        </el-form-item>
      </el-form>
    </el-col>
  </el-row>
</template>

<style lang="scss" scoped>
.login-page {
  height: 100vh;
  background-color: #fff;
  .bg {
    background: url("@/assets/logo2.png") no-repeat 50% center / 240px auto,
      url("@/assets/login_bg.jpg") no-repeat center / cover;
    border-radius: 0 20px 20px 0;
  }
  .form {
    display: flex;
    flex-direction: column;
    justify-content: center;
    user-select: none;
    .title {
      margin: 0 auto;
    }
    .button {
      width: 100%;
    }
    .flex {
      width: 100%;
      display: flex;
      justify-content: space-between;
    }
  }
}
</style>
